package cn.com.thinker.security.sdk.tools;

import cn.com.thinker.core.tools.spring.SpringContextUtils;
import cn.com.thinker.security.sdk.shiro.propertise.ShiroProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Component;

import javax.swing.*;

/**
 * Created by crazyHC on 2017/7/5.
 */

public class SsoUtils {


    /**
     * 当使用thinDs时，进行地址选择
     * @param url
     * @return
     */
    public static String chooseUrl(String url){
        ShiroProperties shiro = SpringContextUtils.getBean(ShiroProperties.class);
        if(shiro!=null && shiro.getSso() !=null&& ! shiro.getSso().isDiret()){
            LoadBalancerClient loadBalancer = SpringContextUtils.getBean(LoadBalancerClient.class);
            if (loadBalancer !=null ) {
                String securityServerUrl = shiro.getSso().getSecurityServerUrl();
                ServiceInstance server = loadBalancer.choose(securityServerUrl);
                String scheme = server.isSecure()?"https://":"http://";
                String thin4soServer =scheme+ server.getMetadata().get("domain")+":"+server.getPort();
                return url.replace(securityServerUrl,thin4soServer);
            }
        }
        return url;
    }
}
